#include "stdafx.h"
#include "mysqlconnpool.h"

CMysqlConnPool::CMysqlConnPool()
{
}

CMysqlConnPool::~CMysqlConnPool()
{
	std::list<CMysqlConn*>::iterator iter = m_IdleConnPool.begin();
	while (iter != m_IdleConnPool.end())
	{
		CMysqlConn* temp = *iter;
		delete temp;
		temp = NULL;
	}
	m_IdleConnPool.clear();
}

void CMysqlConnPool::InitPool(char* url, char* user, char* password, char* dbname, unsigned int port)
{
	for (int i = 0; i < 10; i++)
	{
		CMysqlConn* pCMysqlConn = new CMysqlConn(url, user, password, dbname, port);
		if (pCMysqlConn != NULL)
		{
			pCMysqlConn->InitConn();
			m_IdleConnPool.push_back(pCMysqlConn);
		}
	}	
}

CMysqlConn* CMysqlConnPool::GetAvilibleConn()
{
	CMysqlConn* conn = NULL;
	if (m_IdleConnPool.size() > 0)
	{
		conn = m_IdleConnPool.front();
		if (conn)
		{
			m_IdleConnPool.pop_front();
			return conn;
		}
	}

	return conn;
}

void CMysqlConnPool::BacktoPool(CMysqlConn* conn)
{
	if (conn != NULL && conn->GetConnectionState() == MYSQL_CONN_IDLE)
	{
		m_IdleConnPool.push_back(conn);
	}
}